package cn.glccc.ds.config;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MybatisPlus 自动填充功能配置
 *
 * @author glccc
 * @date 2024-06-07
 */
@Slf4j
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private GlobalConfig globalConfig;

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("公共字段自动填充【insert】...");

        // 拿到当前用户
        String username = "admin";
        // 拿到当前时间
        LocalDateTime now = LocalDateTime.now();
        // 拿到配置中设置的逻辑未删除值
        String logicNotDeleteValue = globalConfig.getDbConfig().getLogicNotDeleteValue();

        this.strictInsertFill(metaObject, "createBy", String.class, username);
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "updateBy", String.class, username);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "delFlag", String.class, logicNotDeleteValue);
        // 自动填充默认版本为0
        this.strictInsertFill(metaObject, "version", Integer.class, 0);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("公共字段自动填充【update】...");

        // 拿到当前用户
        String username = "admin";
        // 拿到当前时间
        LocalDateTime now = LocalDateTime.now();

        this.strictUpdateFill(metaObject, "updateBy", String.class, username);
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, now);
        
    }

}
